package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	rl2 "github.com/juju/ratelimit"
	"go.uber.org/ratelimit"
	"net/http"
	"time"
)

func main() {

}
func Drop() {
	rl := ratelimit.New(1) // per second 表示1秒放行一个
	prev := time.Now()
	for i := 0; i < 10; i++ {
		now := rl.Take() //这里会阻塞直到1秒的时间走完 达到漏桶的效果
		fmt.Println("now:", now.Sub(prev))
		prev = now

	}
}
func RateLimitropMiddleware(rate int) gin.HandlerFunc {
	rl := ratelimit.New(1) // per second 表示1秒放行一个
	return func(c *gin.Context) {
		rl.Take()
		c.Next()
	}
}
func RateLimitMiddleware(fillInterval time.Duration, cap int64) gin.HandlerFunc {
	bucket := rl2.NewBucket(fillInterval, cap)
	return func(c *gin.Context) {
		if bucket.TakeAvailable(1) < 1 {
			c.String(http.StatusOK, "rate limit...")
			c.Abort()
			return
		}
		c.Next()
	}
}
